package com.fbee.smartcommunities.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fbee.smartcommunities.entity.Visitor;
import com.fbee.smartcommunities.mapper.VisitorMapper;
import com.fbee.smartcommunities.service.VisitorService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fbee.smartcommunities.utils.LocalDateTimeUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 汪佳泉
 * @since 2024-08-21
 */
@Service
public class VisitorServiceImpl extends ServiceImpl<VisitorMapper, Visitor> implements VisitorService {

    @Resource
    private VisitorMapper visitorMapper;

    @Override
    public Page<Visitor> getPage(Integer pageNo, Integer pageSize, String keyword, Boolean order) {
        Page<Visitor> visitorPage = new Page<>(pageNo, pageSize);
        QueryWrapper<Visitor> visitorWrapper = new QueryWrapper<>();
        visitorWrapper.eq("deleted",0);
        if(order){
            visitorWrapper.orderByDesc("time");
        }
        if(keyword == null){
            return visitorMapper.selectPage(visitorPage,visitorWrapper);
        } else {
            visitorWrapper.like("phone",keyword).or().like("type",keyword).or().like("name",keyword);
            return visitorMapper.selectPage(visitorPage,visitorWrapper);
        }
    }

    @Override
    public Boolean changeState(Long id, Boolean state, String key) {
        String col;
        if("alw".equals(key)){
            col = "state";
        }else {
            col = "deleted";
        }
        return this.update(new UpdateWrapper<Visitor>().set(col,!state).eq("id",id));
    }

    @Override
    public Boolean addVisitor(Long openId,
                              String name,
                              Boolean sex,
                              String phone,
                              String carId,
                              String purpose,
                              Long visitTimeValue) {
        LocalDateTime localDateTime = LocalDateTimeUtil.valueToLocalDateTime(visitTimeValue);
        return this.save(new Visitor(openId.intValue(),name,sex,phone,carId,purpose,localDateTime));
    }

    @Override
    public List<Visitor> getVisitorsByUid(Long id) {
        return this.list(new QueryWrapper<Visitor>().eq("u_id",id).eq("deleted",0));
    }


}
